import {reactive, ref} from "vue";
import {deleteImg, uploadImg} from "../../api/pictures";
import {useStore} from "vuex";
const BASE_URL = import.meta.env.VITE_PIC_URL

export function useUpload(){

    const {state} = useStore()
    const imgList = reactive<string[]>([])
    const delList = reactive<string[]>([])
    const uploading = ref<boolean>(false)

    async function chooseImg(isCompress: boolean = false){
        const chooseRes = await uni.chooseImage({
            count: 1,
            sizeType:["compressed "]
        })

        let path:string = (chooseRes as any).tempFilePaths[0];

        if(isCompress){
            await uni.compressImage({
                src: path,
                quality: 80,
                width: 'auto',  
                height: 'auto',  
                success: res => {
                  console.log(res.tempFilePath)
                  imgList.push(res.tempFilePath)
                }
            })
        }else{
            imgList.push(path)
        }

    }

    async function upload(FLAG: 'ZP' | 'CNS' = 'ZP'){
        try {
            // const chooseRes = await uni.chooseImage({
            //     count: 1
            // })
            if (imgList.length === 0){
                return
            }
            uploading.value = true
            // console.log({chooseRes})
            // @ts-ignore

            if (imgList[0].startsWith(FLAG)){
                return imgList[0]
            }

            const uploadRes = await uploadImg({
                CUSER_ID: state.user.userInfo.CUSER_ID,
                FLAG,
                filePath: imgList[0]
            })
            imgList[0] = uploadRes.DATA.filename

            return uploadRes.DATA.filename

            // imgList[0] = `${BASE_URL}/browse?picfilename=${uploadRes.DATA.filename}`
        }catch (err){
            // @ts-ignore
            if (err.errMsg !== 'chooseImage:fail cancel'){
                uni.showToast({
                    title: '图片上传失败',
                    icon: 'error',
                    mask: true
                })
            }
        }finally {
            uploading.value = false
        }
    }

    function delImage(){
        // try {
        //     await deleteImg(imgList[0].split('=')[1])
        //     imgList.pop()
        // }catch (err){
        //     console.log(err)
        //     uni.showToast({
        //         title: '删除图片失败',
        //         icon: 'error',
        //         mask: true
        //     })
        // }
        const delImg = imgList.pop()
        if (delImg){
            delList.push(delImg)
        }
    }

    function doDelImg(isDelOld: boolean = false){
        if (isDelOld){
            if (imgList.length > 0 && imgList[0].startsWith(BASE_URL)){
                deleteImg(
                    imgList[0]
                ).then(() => {
                    imgList.pop()
                })
            }
        }else {
            if (delList.length === 0){
                return
            }
        }

        return Promise.all(delList.map(item => new Promise((resolve, reject) => {
            if (item.startsWith(BASE_URL)){
                deleteImg(item).then(resolve).catch(reject)
            }
            // deleteImg(
            //     item.startsWith(BASE_URL) ? item :
            //     `${BASE_URL}/browse?picfilename=${item}`
            // ).then(resolve).catch(reject)

            resolve(null)
        })))
    }

    return {
        imgList,
        uploading,
        delList,
        doDelImg,
        delImage,
        chooseImg,
        upload
    }
}
